<template>
  <div class="app-container">
    <div class="hor mg-b-10">
      <!--      <el-select v-model="isLock" placeholder="是否冻结" clearable @change="onLockChange">-->
      <!--        <el-option-->
      <!--          label="未冻结"-->
      <!--          :value="false">-->
      <!--        </el-option>-->
      <!--        <el-option-->
      <!--          label="已冻结"-->
      <!--          :value="true">-->
      <!--        </el-option>-->
      <!--      </el-select>-->
      <el-select v-model="isFlag" placeholder="是否可用" clearable @change="onFlagChange"
                 class="mg-l-10">
        <el-option
          label="可用"
          :value="1">
        </el-option>
        <el-option
          label="已注销"
          :value="0">
        </el-option>
      </el-select>
      <el-input
        style="width: 200px"
        class="mg-l-10"
        placeholder="请输入姓名"
        v-model="searchName"
        @clear="onInputClear(1)"
        clearable>
      </el-input>
      <el-input
        style="width: 200px"
        class="mg-l-10"
        placeholder="请输入电话"
        v-model="searchPhone"
        @clear="onInputClear(2)"
        clearable>
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="onClickSearch()" class="mg-l-20">搜索
      </el-button>
      <div class="flex1"></div>
      <el-button type="primary" icon="el-icon-plus" class="mg-l-10"
                 @click="onClickAdd()"></el-button>
      <el-button-group class="mg-l-10">
        <el-button type="success" @click="batchLock(2)">启用</el-button>
        <el-tooltip class="item" effect="dark" content="禁用后无法登陆" placement="bottom">
          <el-button type="danger" @click="batchLock(1)">禁用</el-button>
        </el-tooltip>

        <!--        <el-button type="success" @click="batchDelete(2)">启用</el-button>-->
        <el-tooltip class="item" effect="dark" content="删除账户无法正常使用" placement="bottom">
          <el-button type="danger" @click="batchDelete(1)">删除</el-button>
        </el-tooltip>

      </el-button-group>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="allList"
      :height="autoHeight"
      element-loading-text="Loading"
      @cell-click="onCellClick"
      @selection-change="handleSelectionChange"
      @row-click="onItemClick"
      @row-dblclick="onItemDoubleClick"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="头像" width="80">
        <template slot-scope="scope">
          <div class="ver ver-center hor-center">
            <el-avatar fit="cover" :src="scope.row.avatarUrl+'?imageView2/1/w/50/h/50'"></el-avatar>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="ID" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ scope.row.id}}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="姓名">
        <template slot-scope="scope">
          <div class="ver">
            <div>姓名：{{ scope.row.name }}</div>
            <div>昵称：{{ scope.row.nickName }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账号" width="200">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.gender==1?'男':((scope.row.gender==null||scope.row.gender==0)?'未知':'女') }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="启用状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.locked" type="danger">禁用</el-tag>
          <el-tag v-else type="success">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="系统角色" width="110" align="center">
        <template slot-scope="scope">
          <el-tag type="info" v-for="(item,index) in scope.row.authRoles" v-bind:key="index">
            {{item.name}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <div class="ver hor-center">
            <el-button type="warning"   size="small"
                       @click.stop="onClickView(scope.row)">查看
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="hor">
      <div class="flex1"></div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mg-t-10">
      </el-pagination>
    </div>
    <el-dialog
      title="编辑用户信息"
      :visible.sync="userInfoDialogShow"
      width="600px"
      @open="onDialogOpen"
      :close-on-click-modal=false
      center>
      <div class="ver match-width">
        <el-form label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号">
                <el-input v-model="userDetail.username"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码">
                <el-input v-model="userDetail.password" type="password"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户姓名">
                <el-input v-model="userDetail.name"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号">
                <el-input v-model="userDetail.phone" type="number"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="性别">
            <el-radio-group v-model="userDetail.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
              <el-radio label="0">未知</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="公司">
            <el-select v-model="userDetail.company.id" placeholder="区域公司" clearable
                       class="" v-if="userDetail.company!=null">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>

          </el-form-item>
          <el-form-item label="权限角色">
            <el-select v-model="selectRoles" multiple placeholder="请选择角色"
                       @change="onRoleChange" class="match-width">
              <el-option
                v-for="item in allRole"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>

            <!--            <el-tag type="" v-for="(item,index) in userDetail.authRoles" v-bind:key="index">-->
            <!--              {{item.name}}-->
            <!--            </el-tag>-->
          </el-form-item>
          <el-form-item label="绑定项目" v-if="!hasAdmin">
            <el-select v-model="selectProjects"  multiple placeholder="请选择项目" class="match-width" filterable>
              <el-option
                v-for="item in allProject"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>

          </el-form-item>
        </el-form>


        <div class="hor match-width ver-center hor-center"
             v-if="isHadPermission(['userOperateAccess'])">
          <el-button @click="userInfoDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="onClickSave" :loading="onSaveLoading">确 定</el-button>
        </div>

      </div>
    </el-dialog>
  </div>

</template>
<style>
</style>
<script>
  import {getList, batchLock, batchDelete, queryRoleList, saveUser} from '@/api/auth/auth'
  const requestProject = require('@/api/project/project')

  const requestCompany = require('@/api/project/company')

  export default {
    filters: {
      // statusFilter(status) {
      //   const statusMap = {
      //     published: 'success',
      //     draft: 'gray',
      //     deleted: 'danger'
      //   }
      //   return statusMap[status]
      // }
    },
    data() {
      return {
        allList: null,
        allRole: null,
        hasSuperManagerRoleId:[],
        allProject: null,
        page: 1,
        size: 20,
        total: 0,
        hasAdmin:false,
        autoHeight: 800,//根据屏幕高度自动计算的高度
        //筛选参数
        params: {},
        isLock: '',
        isFlag: '',
        searchName: '',
        searchPhone: '',
        selectRowList: [],

        //信息窗口
        userInfoDialogShow: false,
        userDetail: {},
        selectRoles: [],
        selectProjects: [],
        onSaveLoading: false,
        levelList: [
          {name: "一级", value: 1}
          , {name: "二级", value: 2}
          , {name: "三级", value: 3}
          , {name: "四级", value: 4}
          , {name: "五级", value: 5}],
        companyList: [],

        listLoading: true
      }
    }, beforeMount() {
      this.authHeight = document.body.scrollHeight - 190
    }, mounted() {
      this.getCompanyList();
      this.fetchData()
    },
    created() {
    },
    methods: {
      fetchData() {
        this.listLoading = true
        const data = new FormData()
        for (var key in this.params) {//直接去除掉空值的对象
          if (this.isEmpty(this.params[key])) {
            delete this.params[key]
          }
        }
        this.params['flag'] = 1
        data.append('params', JSON.stringify(this.params))
        data.append('page', this.page)
        data.append('size', this.size)
        data.append('sortJsonStr', null)

        getList(data).then(response => {
          this.allList = response.data
          for (let i = 0; i < this.allList.length; i++) {
            if (this.allList[i].gender == null) {//为空的默认为0
              this.allList[i].gender = 0
            }
            this.allList[i].gender += ''
          }
          this.total = response.totalElements
          this.getRoleList()
          this.listLoading = false
        })
      }, batchLock(operate) {
        if (!this.isHadPermission(['userOperateAccess'])) {
          this.noPermissionHint()
          return
        }

        const _this = this
        if (this.selectRowList == null || this.selectRowList.length == 0) {
          this.$message({
            message: '请选择对象',
            type: 'warning',
            duration: 1000
          })
          return
        }
        const array = []
        for (let i = 0; i < this.selectRowList.length; i++) {
          array.push(this.selectRowList[i].id)
        }
        const data = new FormData()
        data.append('ids', array)
        data.append('operate', operate)

        this.$message({
          message: '操作中',
          type: 'success',
          duration: 1000
        })

        batchLock(data).then(response => {
          this.$message({
            message: operate === 1 ? '冻结成功' : '解冻成功',
            type: 'success',
            duration: 3000
          })
          _this.fetchData()
        })
      }, batchDelete(operate) {
        if (!this.isHadPermission(['userOperateAccess'])) {
          this.noPermissionHint()
          return
        }
        const _this = this
        if (this.selectRowList == null || this.selectRowList.length == 0) {
          this.$message({
            message: '请选择对象',
            type: 'warning',
            duration: 1000
          })
          return
        }
        const array = []
        for (let i = 0; i < this.selectRowList.length; i++) {
          array.push(this.selectRowList[i].id)
        }
        const data = new FormData()
        data.append('ids', array)
        data.append('operate', operate)

        this.$message({
          message: '操作中',
          type: 'success',
          duration: 1000
        })

        batchDelete(data).then(response => {
          this.$message({
            message: operate === 1 ? '删除成功' : '启用成功',
            type: 'success',
            duration: 3000
          })
          _this.fetchData()
        })
      }, getProjectList() {
        let that = this;
        const data = new FormData()
        data.append('page', 1)
        data.append('size', 99999)

        data.append('params', JSON.stringify({flag: 1}))
        const sortList = []
        sortList.push(
          {
            direction: 'desc',
            property: 'createTime'
          }
        )
        data.append('sortJsonStr', JSON.stringify(sortList))
        requestProject.getList(data).then(response => {
          that.allProject = response.data;
          that.selectProjects = [];
          if (that.userDetail.projectIds != null) {
            var ids = that.userDetail.projectIds.split(",");
            for (var i = 0; i < ids.length; i++) {
              var id = parseInt(ids[i]);
              var flag = false;
              for (var j = 0; j < that.allProject.length; j++) {
                if (that.allProject[j].id == id) {
                  flag = true;
                  break;
                }
              }
              if (flag) {
                that.selectProjects.push(id);
              }


            }
          }
        })
      },
      hasAdminMethod(){
        this.hasAdmin = false;
        for (var i = 0; i < this.hasSuperManagerRoleId.length; i++) {
          if (this.selectRoles.includes(this.hasSuperManagerRoleId[i])) {
            this.hasAdmin = true
            break;
          }
        }
      },
      getRoleList() {

        const data = new FormData()
        queryRoleList(data).then(response => {
          this.allRole = response.data
          for (var i = 0; i < this.allRole.length; i++) {
            var authAccessesList = this.allRole[i].authAccesses;
            var flag = false;
            for (var j = 0; j < authAccessesList.length; j++) {
              if (authAccessesList[j].name == "superManager") {
                flag = true;
                break
              }
            }
            if (flag) {
              this.hasSuperManagerRoleId.push(this.allRole[i].id)
              continue
            }
          }
        })
      }, saveUser() {

        this.onSaveLoading = true
        //把选择的角色赋值过去
        if (this.selectRoles != null) {
          this.userDetail.authRoles = []
          for (let i = 0; i < this.selectRoles.length; i++) {
            for (let j = 0; j < this.allRole.length; j++) {
              if (this.selectRoles[i] === this.allRole[j].id) {
                this.userDetail.authRoles.push(this.allRole[j])
              }
            }
          }
        }
        if (this.selectProjects != null) {
          this.userDetail.projectIds = "";
          for (let i = 0; i < this.selectProjects.length; i++) {
            this.userDetail.projectIds += this.selectProjects[i] + ","
          }
          if (this.userDetail.projectIds.length > 1){
            this.userDetail.projectIds = this.userDetail.projectIds.substring(0,this.userDetail.projectIds.length - 1)
          }
        }
        if (this.isEmpty(this.userDetail.company.id)) {
          delete this.userDetail.company;
        }
        const data = new FormData();
        data.append('json', JSON.stringify(this.userDetail))
        saveUser(data).then(response => {
          this.onSaveLoading = false
          this.userInfoDialogShow = false
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }).catch((e) => {
          this.onSaveLoading = false
        })
      }, getCompanyList() {

        let par = {
          flag: 1,
          level: 1
        };
        const data = new FormData()
        data.append('params', JSON.stringify(par))
        data.append('page', this.page)
        data.append('size', this.size)
        requestCompany.getList(data).then(response => {
          this.companyList = response.data;
        }).catch((e) => {
          this.onSaveLoading = false
        })
      }
      , handleSizeChange(val) {
        this.size = val
        this.fetchData()
      }, handleCurrentChange(val) {
        this.page = val
        this.fetchData()
      }, onLockChange(val) {
        this.params.locked = val
        this.fetchData()
      }, onFlagChange(val) {
        this.params.flag = val + ''
        this.fetchData()
      }, onClickSearch() {//点击搜索
        if (!this.isEmpty(this.searchName)) {
          this.params['name_like'] = ('%' + this.searchName.trim() + '%')
        } else {
          this.params['name_like'] = ''
        }
        if (!this.isEmpty(this.searchPhone)) {
          this.params['phone_like'] = ('%' + this.searchPhone.trim() + '%')
        } else {
          this.params['phone_like'] = ''
        }
        if (!this.isEmpty(this.searchNum)) {
          this.params['num_like'] = ('%' + this.searchNum.trim() + '%')
        } else {
          this.params['num_like'] = ''
        }

        this.fetchData()
      }, onInputClear(type) {//1.姓名
        if (type === 1) {
          this.searchName = ''
        } else if (type === 2) {
          this.searchPhone = ''
        } else if (type === 3) {
          this.searchNum = ''
        }
        this.onClickSearch()

      }, handleSelectionChange(rowList) {//多选变化监听
        this.selectRowList = rowList
      }, onCellClick(row, column, cell, event) {
        if (column.type == 'selection') {
          this.$refs.table.toggleRowSelection(row)
        }
      }
      , onItemClick(row) {//单行点击
      }
      , onItemDoubleClick(row) {//单行双击
        this.userInfoDialogShow = true
        this.userDetail = row
        if (this.userDetail.organization == null) {
          this.userDetail.organization = {}
        }
        if (this.userDetail.position == null) {
          this.userDetail.position = {}
        }
        if (this.userDetail.company == null) {
          this.userDetail.company = {}
        }
        // console.log(this.userDetail)
      }
      , onClickAdd() {
        if (!this.isHadPermission(['userOperateAccess'])) {
          this.noPermissionHint()
          return
        }

        this.userDetail = {
          organization: {},
          position: {},
          company: {}
        }
        this.userInfoDialogShow = true
      }, onDialogOpen() {
        this.getRoleList()
        //拼装角色列表选择
        // this.selectRoles.splice(0, this.selectRoles.length)
        this.selectRoles = [];
        if (this.userDetail.authRoles != null) {
          for (let i = 0; i < this.userDetail.authRoles.length; i++) {
            this.selectRoles.push(this.userDetail.authRoles[i].id)
          }
        }
        let that = this
        that.hasAdminMethod();

        this.getProjectList();

        // console.log(this.userDetail)
        // setTimeout(function () {
        // if (this.userDetail.organization != null && !this.isEmpty(this.userDetail.organization.id)) {
        //   this.getPositionList(this.userDetail.organization.id)
        // }
        // }, 1000);
      }, onRoleChange(val) {
        this.selectRoles = val;
        this.hasAdminMethod();
      }, onClickSave() {//点击保存
        this.saveUser()
      }, onClickView(row) {
        this.userInfoDialogShow = true
        this.userDetail = row
        if (this.userDetail.organization == null) {
          this.userDetail.organization = {}
        }
        if (this.userDetail.position == null) {
          this.userDetail.position = {}
        }
        if (this.userDetail.company == null) {
          this.userDetail.company = {}
        }
      }, onTypeChange(val) {
        for (let i = 0; i < this.itemList.length; i++) {
          if (this.itemList[i].id == val) {
            this.userDetail.type = this.itemList[i].type
          }
        }
      }
    }
  }
</script>
